﻿using drinking.Api;
using drinking.Helpers;
using drinking.Models;
using SKIT.FlurlHttpClient.Wechat.TenpayV3;
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Models;
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Settings;
namespace drinking.Managers
{
    /// <summary>
    /// 支付控制
    /// </summary>
    public class WxPayManager
    {
        // private static WechatTenpayClient payClient;
        private static WechatTenpayClient PayClient = new (new WechatTenpayClientOptions()
        {
            MerchantId = "微信商户号",
            MerchantV3Secret = "微信商户 v3 API 密钥",
            MerchantCertificateSerialNumber = "微信商户证书序列号",
            MerchantCertificatePrivateKey = "-----BEGIN PRIVATE KEY-----微信商户证书私钥-----END PRIVATE KEY-----",
            PlatformCertificateManager = new InMemoryCertificateManager()
        });

        /// <summary>
        /// 生成商户订单和
        /// </summary>
        /// <param name="order"></param>
        /// <param name="openid"></param>
        /// <returns></returns>
        /// <exception cref="Exception_"></exception>
        public static (string OutTradeNum, string PrepayId) CreatePayTransaction(Order order)
        {
            var request = new CreatePayTransactionJsapiRequest()
            {
                OutTradeNumber = $"{DateTime.Now:yyyyMMddHHmmssfff}{order.OrderId}",
                AppId = WxManager.APPID,
                Description = $"餐饮消费-饮品",
                ExpireTime = DateTimeOffset.Now.AddMinutes(15),
                NotifyUrl = "http://example.com/api/wx/order/payCallBack",
                Amount = new CreatePayTransactionJsapiRequest.Types.Amount()
                {
                    Total = Convert.ToInt32(order.Amount * 100)
                },
                Payer = new CreatePayTransactionJsapiRequest.Types.Payer()
                {
                    OpenId = UserManager.CurrCustomer.Value.Openid,
                }
            };

            
            var response = PayClient.ExecuteCreatePayTransactionJsapiAsync(request).Result;
            if (!response.IsSuccessful())
            {
                // 获取支付 PrepayId 失败
               /* Console.WriteLine("HTTP 状态：" + response.RawStatus);
                Console.WriteLine("错误代码：" + response.ErrorCode);
                Console.WriteLine("错误描述：" + response.ErrorMessage);*/
                throw new Exception_(ResultCode.NO_OK, response.ErrorMessage);
            }

            return (request.OutTradeNumber, response.PrepayId);

            
        }

        /// <summary>
        /// 生成微信支付参数
        /// </summary>
        /// <param name="prepayId"></param>
        /// <returns></returns>
        public static IDictionary<string, string> CreatePayParams(string prepayId)
        {
            return PayClient.GenerateParametersForJsapiPayRequest(WxManager.APPID, prepayId);
        }


        /// <summary>
        /// 主动查询支付状态
        /// </summary>
        /// <param name="outTradeNumber">商户订单号</param>
        /// <returns></returns>
        public static bool QueryPayResult(string outTradeNumber)
        {

           var response =  PayClient.ExecuteGetPayTransactionByOutTradeNumberAsync(new GetPayTransactionByOutTradeNumberRequest()
            {
                OutTradeNumber = outTradeNumber,
            }).Result;

            if(response.IsSuccessful())
            {
                string tradeState = response.TradeState;
                /*
                SUCCESS：支付成功
                REFUND：转入退款
                NOTPAY：未支付
                CLOSED：已关闭
                REVOKED：已撤销（仅付款码支付会返回）
                USERPAYING：用户支付中（仅付款码支付会返回）
                PAYERROR：支付失败（仅付款码支付会返回）*/
                if (tradeState == "SUCCESS")
                {
                    // 支付成功
                    return true;
                }
            }
            return false;
        }
            


        /// <summary>
        /// 支付结果回调
        /// </summary>
        public static void PayCallBack(string callbackJson,
           string callbackTimestamp,
           string callbackNonce,
           string callbackSignature,
           string callbackSerialNumber )
        {
            bool valid = PayClient.VerifyEventSignature(callbackTimestamp, callbackNonce, callbackJson, callbackSignature, callbackSerialNumber);
            if (valid)
            {
                /* 将 JSON 反序列化得到通知对象 */
                var callbackModel = PayClient.DeserializeEvent(callbackJson);
                if ("TRANSACTION.SUCCESS".Equals(callbackModel.EventType))
                {
                    /* 根据事件类型，解密得到支付通知敏感数据 */
                    var callbackResource = PayClient.DecryptEventResource<SKIT.FlurlHttpClient.Wechat.TenpayV3.Events.TransactionResource>(callbackModel);
                    string outTradeNumber = callbackResource.OutTradeNumber;
                    string transactionId = callbackResource.TransactionId;
                    var db = new DBContext().Db;
                    Order order = db.Queryable<Order>().Where(o => o.OutTradeNo == outTradeNumber).First();
                    if (order != null && order.OrderStatus == 0)
                    {
                        order.OrderStatus = 10;
                        order.PayTime = callbackResource.SuccessTime.ToString("yyyy/MM/dd HH:mm:ss");
                        db.Updateable(order).UpdateColumns(o => new { order.OrderStatus, order.PayTime }).ExecuteCommand();

                    }
                    
                }
            }
        }








    }
}
